#!/bin/sh /etc/rc.common
# Copyright (C) 2014 OpenWrt.org

START=99

USE_PROCD=1

#PROCD_DEBUG=1

NAME=asterisk
COMMAND=/usr/sbin/$NAME

LOGGER="/usr/bin/logger -p user.err -s -t $NAME --"

start_service() {
  local enabled

  local user
  local group

  local log_stderr
  local log_stdout

  local agidir
  local cdrcsvdir
  local datadir
  local dbdir
  local keydir
  local logdir
  local rundir
  local spooldir
  local varlibdir

  local options

  config_load $NAME

  config_get_bool enabled general enabled 0
  if [ $enabled -eq 0 ]; then
    $LOGGER service not enabled in /etc/config/$NAME
    exit 1
  fi

  config_get user  general user  $NAME
  config_get group general group $NAME

  user_exists "$user" || {
    $LOGGER user \""$user"\" does not exist
    exit 1
  }
  group_exists "$group" || {
    $LOGGER group \""$group"\" does not exist
    exit 1
  }

  if [ "$user" = $NAME ]; then
    if ! id -nG $NAME | grep -qwF dialout; then
      group_exists dialout && group_add_user dialout $NAME
    fi
  fi

  config_get_bool log_stderr general log_stderr 1
  config_get_bool log_stdout general log_stdout 1

  config_get agidir    directories agidir    /usr/share/$NAME/agi-bin
  config_get datadir   directories datadir   /usr/share/$NAME
  config_get dbdir     directories dbdir     /var/lib/$NAME/astdb
  config_get keydir    directories keydir    /usr/share/$NAME/keys
  config_get logdir    directories logdir    /var/log/$NAME
  config_get rundir    directories rundir    /var/run/$NAME
  config_get spooldir  directories spooldir  /var/spool/$NAME
  config_get varlibdir directories varlibdir /var/lib/$NAME

  config_get options general options

  cdrcsvdir="${logdir}/cdr-csv"

  # do not touch directories that already exist
  # posix shell does not support arrays, hence using awk
  awk \
    -v user="$user" \
    -v group="$group" \
    -v a="$agidir" \
    -v b="$cdrcsvdir" \
    -v c="$datadir" \
    -v d="$dbdir" \
    -v e="$keydir" \
    -v f="$logdir" \
    -v g="$rundir" \
    -v h="$spooldir" \
    -v i="$varlibdir" \
    '
      BEGIN {
        dir[0]=a
        dir[1]=b
        dir[2]=c
        dir[3]=d
        dir[4]=e
        dir[5]=f
        dir[6]=g
        dir[7]=h
        dir[8]=i
        for (x in dir) {
          if (system("test ! -e \"" dir[x] "\"" )) {
            delete dir[x]
          }
        }
        for (x in dir) {
          system("mkdir -p \"" dir[x] "\"" )
          system("chmod 750 \"" dir[x] "\"" )
          system("chown \"" user "\":\"" group "\" \"" dir[x] "\"" )
        }
      }
    '

  chown -R "$user":"$group" /etc/$NAME

  procd_open_instance
  procd_set_param command $COMMAND
  procd_append_param command \
    -G "$group" \
    -U "$user" \
    $options \
    -f
  # forward stderr to logd
  procd_set_param stderr $log_stderr
  # same for stdout
  procd_set_param stdout $log_stdout
  procd_close_instance
}

